// 主题管理工具

// 主题模式枚举
export const ThemeMode = {
  LIGHT: 'light',
  DARK: 'dark',
  SYSTEM: 'system'
}

// 获取当前主题模式
export function getCurrentTheme() {
  return localStorage.getItem('theme') || ThemeMode.SYSTEM
}

// 检测系统偏好
export function getSystemPreference() {
  return window.matchMedia('(prefers-color-scheme: dark)').matches ? 
    ThemeMode.DARK : ThemeMode.LIGHT
}

// 应用主题到文档
export function applyTheme(mode) {
  const isDark = mode === ThemeMode.DARK || 
    (mode === ThemeMode.SYSTEM && getSystemPreference() === ThemeMode.DARK)
  
  if (isDark) {
    document.documentElement.classList.add('dark')
  } else {
    document.documentElement.classList.remove('dark')
  }
}

// 设置主题
export function setTheme(mode) {
  if (Object.values(ThemeMode).includes(mode)) {
    localStorage.setItem('theme', mode)
    applyTheme(mode)
    return true
  }
  return false
}

// 初始化主题
export function initTheme() {
  const savedTheme = getCurrentTheme()
  applyTheme(savedTheme)
  
  // 监听系统主题变化
  if (savedTheme === ThemeMode.SYSTEM) {
    window.matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', () => applyTheme(ThemeMode.SYSTEM))
  }
}